<template>
  <Dialog v-model="dialogVisible" title="定价数据权限维护" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="授权用户" prop="authUserId">
        <CascaderUser
          :options="{multiple: true}"
          v-model="formData.authUserId"
          placeholder="请选择授权用户（可多选）"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确 定</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import {getPriceAuthList, PriceAuth, savePriceAuth} from '@/api/business/operation/price/auth'
import {useUserStore} from '@/store/modules/user'

const message = useMessage()
const userStore = useUserStore()

const dialogVisible = ref(false)
const formLoading = ref(false)
const formRef = ref()

// 表单数据
const formData = ref({
  userId: undefined,
  authUserId: [] // 授权用户ID数组
})

// 已有的授权记录列表
const existingAuthList = ref<PriceAuth[]>([])

const formRules = reactive({
  authUserId: [{required: true, message: '请选择授权用户', trigger: 'change'}]
})

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  resetForm()

  // 获取当前用户ID
  const currentUserId = userStore.user.id.toString()

  // 加载已有的授权数据
  try {
    formLoading.value = true
    const data = await getPriceAuthList(currentUserId)
    console.log('已存在的授权数据', data)
    if (data && Array.isArray(data)) {
      formData.value.authUserId = data
        .filter(item => item.authUserId)
        .map(item => item.authUserId)
    }
  } catch (error) {
    console.log('加载权限数据失败', error)
  } finally {
    formLoading.value = false
  }
}

/** 提交表单 */
const submitForm = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return

  try {
    formLoading.value = true
    const currentUserId = formData.value.userId
    await savePriceAuth({
      userId: currentUserId,
      authUserId: Array.isArray(formData.value.authUserId)
        ? formData.value.authUserId.join(',')
        : formData.value.authUserId,
    })


    message.success('保存成功')
    dialogVisible.value = false
  } catch (error) {
    console.error('保存失败', error)
    message.error('保存失败')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userId: undefined,
    authUserIds: []
  }
  existingAuthList.value = []
  formRef.value?.resetFields()
}

defineExpose({open})
</script>
